package io.geekidea.boot.chargeback.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.geekidea.boot.area.entity.Area;
import io.geekidea.boot.area.query.AreaQuery;
import io.geekidea.boot.auth.util.LoginUtil;
import io.geekidea.boot.chargeback.dto.AddChargeBack;
import io.geekidea.boot.chargeback.dto.ChargeBackExcel;
import io.geekidea.boot.chargeback.entity.ChargeBack;
import io.geekidea.boot.chargeback.mapper.ChargeBackMapper;
import io.geekidea.boot.chargeback.query.ChargeBackQuery;
import io.geekidea.boot.chargeback.service.ChargeBackService;
import io.geekidea.boot.chargeback.vo.ChargeBackVo;
import io.geekidea.boot.common.PageDto;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.insurancePolicy.entity.InsurancePolicy;
import io.geekidea.boot.insurancePolicy.service.InsurancePolicyService;
import io.geekidea.boot.persmanag.dto.PersManagExcel;
import io.geekidea.boot.persmanag.query.PersManagQuery;
import io.geekidea.boot.salesslip.entity.Salesslip;
import io.geekidea.boot.salesslip.mapper.SalesslipMapper;
import io.geekidea.boot.salesslip.query.SalesslipQuery;
import io.geekidea.boot.salesslip.service.SalesslipService;
import io.geekidea.boot.store.entity.OneStore;
import io.geekidea.boot.store.entity.Store;
import io.geekidea.boot.store.service.StoreService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 退单管理控制器
 * @since 2023-12-7
 */

@Slf4j
@RestController
@RequestMapping("/chargeBack")
@Tag(name = "退单管理")
public class ChargeBackController {

    @Resource
    private ChargeBackService chargeBackService;
    @Resource
    private SalesslipService salesslipService;
    @Resource
    private StoreService storeService;
    @Resource
    private SalesslipMapper salesslipMapper;
    @Resource
    private InsurancePolicyService insurancePolicyService;
    @Resource
    private ChargeBackMapper chargeBackMapper;

    /**
     * 退单分页列表
     * @param chargeBackQuery
     * @return
     * @throws Exception
     */
    @Operation(summary = "退单管理分页列表")
    @PostMapping("/list")
    public ApiResult chargeBack(@RequestBody ChargeBackQuery chargeBackQuery) throws Exception {
        List<ChargeBack> chargeBacks = chargeBackService.chargeBackLick(chargeBackQuery);
        int total = chargeBackService.getTotal(chargeBackQuery).getTotal();
        PageDto pageDto = new PageDto(chargeBacks,total,chargeBackQuery.getPageSize(),chargeBackQuery.getPageIndex() +1);
        return ApiResult.success(pageDto);
    }

//    @Operation(summary = "添加")
//    @PostMapping("/ById")
//    public ApiResult getChargeById(@RequestBody ChargeBack chargeBack) throws Exception {
//        System.out.println(chargeBack);
//        chargeBack.setCreatorUser(Math.toIntExact(LoginUtil.getUserId()));
//
//        boolean b = chargeBackService.addChargeById(chargeBack);
//        if (!b){
//            return ApiResult.success("添加失败",b);
//        }
//       return b;
//    }



    @Operation(summary = "添加")
    @PostMapping("/ByAddOutId")
    public ApiResult ByAddOutId(@RequestBody AddChargeBack addChargeBack) throws Exception {

        Integer storeId = addChargeBack.getStoreId();
        OneStore oneStore = storeService.getOneStore(storeId);
        String code = oneStore.getCode();
        String str = generateOrderNumber(code);
        addChargeBack.setNumbers(str);
        addChargeBack.setOrderTypes("销售");

        addChargeBack.setPreparedBy(LoginUtil.getUsername());

        ChargeBack chargeBack = new ChargeBack();
        BeanUtil.copyProperties(addChargeBack,chargeBack);

        int insert = chargeBackMapper.insert(chargeBack);

        if (insert<0) {
            return ApiResult.success("退单失败，请和管理员沟通");
        }

        return ApiResult.success("退单成功");


    }



    @PostMapping("/getNumbersList")
    public ApiResult getNumbersList(){

        List<Salesslip> list = salesslipService.list();

        return ApiResult.success(list);
    }

    @PostMapping("/getMaterial/{id}")
    public ApiResult getMaterial (@PathVariable Integer id){
        Salesslip salesslip = salesslipMapper.selectById(id);
        return ApiResult.success(salesslip);
    }

    @PostMapping("/getStore")
    public ApiResult getStore (){

        List<Store> list = storeService.list();

        return ApiResult.success(list);
    }
    public String generateOrderNumber(String storeCode) {
        LocalDateTime now = LocalDateTime.now();
        String formattedDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long sequenceNumber = new Date().getTime();
        return "td_" + storeCode + "_" + formattedDate + "_" + sequenceNumber;
    }




    @PostMapping("/download")
    @Operation(tags = "Post",description = "下载文件")
    public void download(@RequestBody  ChargeBackQuery chargeBackQuery, HttpServletResponse response){
        //WarehousentryQuery warehousentryQuery = new WarehousentryQuery();

        List<ChargeBackExcel> list = chargeBackMapper.DownloadList(chargeBackQuery);
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            String excelName = URLEncoder.encode("退单管理"+ LocalDateTime.now(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
            // 以字节流的形式输出响应正文
            outputStream = response.getOutputStream();
            try (ExcelWriter excelWriter = EasyExcel.write(outputStream, ChargeBackExcel.class).build()) {
                WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
                excelWriter.write(list,writeSheet);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}